package com.warmlight.voicepacket.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.AbsListView;


/**
 * 上拉加载的RecycleView
 * Created by color on 16/5/31.
 */

public class LoadRecyclerView extends RecyclerView {

    GestureDetector mGestureDetector;

    int totalItemCount; //总item数量
    int lastVisibleItem; //最后一个显示的item的位置
    private LoadListener loadListener;
    //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
    boolean isSlidingToLast = false;
    private boolean isHaveData = false; // 标示是否还有数据可加载

    Context mContext;
    RecyclerView recyclerView;


    public void setIsHaveData(boolean isHaveData) {
        this.isHaveData = isHaveData;
    }

    public void setLoadListener(LoadListener loadListener) {
        this.loadListener = loadListener;
    }

    public LoadRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public LoadRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent ev) {
                //Log.i("CommunityRecyclerView", "点击了recyclerview");
                performClick();
                return true;
            }
        });

        this.mContext = context;
        recyclerView = this;

        this.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LayoutManager layoutManager = recyclerView.getLayoutManager();
                    if (layoutManager instanceof LinearLayoutManager) {
                        //获取最后一个完全显示的ItemPosition
                        LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                        int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = manager.getItemCount();
                        // 判断是否滚动到底部，并且是向右滚动
//                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);

                        if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                            //加载更多功能的代码
                            if (!isHaveData) {
                                //数据加载完成时调用
//                                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                                loadListener.onLoad();
                            } else {
                                //无更多数据时调用
//                                RecyclerViewStateUtils.setFooterViewState(getContext(), recyclerView, 21, LoadingFooter.State.TheEnd, null); //21
                                loadListener.loadFinish();
                            }
                        }
                    } else if (layoutManager instanceof GridLayoutManager) {
                        GridLayoutManager manager = (GridLayoutManager) layoutManager;
                        int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = manager.getItemCount();
                        // 判断是否滚动到底部，并且是向右滚动
                        if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                            //加载更多功能的代码
                            if (!isHaveData) {
                                loadListener.onLoad();
                            } else {
                                loadListener.loadFinish();
                            }
                        }
                    } else if (layoutManager instanceof StaggeredGridLayoutManager) {

                        StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
                        int column = staggeredGridLayoutManager.getColumnCountForAccessibility(null, null);
                        int[] positions = new int[column];
                        staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(positions);

                        for (int i = 0; i < positions.length; i++) {
                            if (positions[i] >= staggeredGridLayoutManager.getItemCount() - column
                                    &&
                                    staggeredGridLayoutManager.findViewByPosition(positions[i]).getBottom() <= getHeight()) {
                                if (!isHaveData) {
                                    loadListener.onLoad();
                                } else {
                                    loadListener.loadFinish();
                                }

                                break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


                if (dy > 0) {
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        //Log.i("CommunityRecyclerView", e.getAction()+"");
        mGestureDetector.onTouchEvent(e);

        return super.onTouchEvent(e);
    }


    public interface LoadListener {

        void onLoad();

        void loadFinish();

    }
}
